package leetcode.code1718;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int[] constructDistancedSequence(int n) {
		int[] ans = new int[(n << 1) - 1];
		PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);
		for (int i = 1; i <= n; i++) {
			queue.add(i);
		}
		Arrays.fill(ans, -1);
		boolean ok = this.find(ans, 0, queue);
		return ans;
	}

	private boolean next(int[] ans, int index, PriorityQueue<Integer> queue, List<Integer> list) {
		while (index < ans.length && ans[index] != -1) {
			index++;
		}
		PriorityQueue<Integer> nextQueue = new PriorityQueue<>((a, b) -> b - a);
		nextQueue.addAll(queue);
		nextQueue.addAll(list);
		return this.find(ans, index, nextQueue);
	}

	private boolean find(int[] ans, int index, PriorityQueue<Integer> queue) {
		if (queue.isEmpty()) {
			return true;
		}
		List<Integer> list = new ArrayList<>();
		while (!queue.isEmpty()) {
			int cur = queue.poll();
			int next = index + cur;
			if (cur == 1) {
				ans[index] = cur;
				if (this.next(ans, index, queue, list)) {
					return true;
				}
				ans[index] = -1;
			} else if (next < ans.length && ans[next] == -1) {
				ans[index] = cur;
				ans[next] = cur;
				if (this.next(ans, index, queue, list)) {
					return true;
				}
				ans[index] = -1;
				ans[next] = -1;
			}
			list.add(cur);
		}
		return false;
	}

	@Override
	public void debug4() {
		H.compare(H.str2array3("[3,1,2,3,2]"), this.constructDistancedSequence(3));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
